<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Api\Service\Ucenter\Controllers;

use Framework\BaseClass\Api\Controller;
use App\Eloquent\Ygt\User;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\ImgUpload;
use App\Eloquent\Ygt\Sms;
use App\Engine\Func;

use App\Eloquent\Province;
use App\Eloquent\City;
use App\Eloquent\Area;

class IndexController extends Controller
{

    public function index()
    {
        $userId        = Func::getHeaderValueByName( 'userid' );
        $fields         = 'id,mobile,mobile_hide,truename,truename_hide,avatar,sex,birth_time,';
        $fields         .= 'company_id,province_id,city_id,area_id';
        $user           = User::getInfo( ['id'=>$userId], $fields );
        if( !$user ){
            xThrow( ERR_PARAMETER );
        }

        $provinceList  = Province::all()->toArray();
        $cityList      = City::all()->toArray();
        $areaList      = Area::all()->toArray();
        $provinceName  = $cityName = $areaName = $address = '';
        foreach( $provinceList as $key=>$val ){
            if( $val['provinceID'] == $user['province_id'] ){
                $provinceName  = $val['province'];
            }
        }
        foreach( $cityList as $key=>$val ){
            if( $val['cityID'] == $user['city_id'] ){
                $cityName      = $val['city'];
            }
        }
        foreach( $areaList as $key=>$val ){
            if( $val['areaID'] == $user['area_id'] ){
                $areaName      = $val['area'];
            }
        }
        $address                = $provinceName.' '.$cityName.' '.$areaName;
        $address                = $address ? $address : '未填写';
        $user['province_name']  = $provinceName;
        $user['city_name']      = $cityName;
        $user['area_name']      = $areaName;
        $user['address']        = $address;
        $sexArr                 = [0=>'未填写',1=>'男',2=>'女'];
        $user['sex_name']       = $sexArr[$user['sex']];
        $birth_day               = '';
        if( $user['birth_time'] ){
            $birth_day          = date( 'Y-m-d', $user['birth_time'] );
        }
        $user['birth_day']      = $birth_day;
        $shortName             = Func::getShortStr( $user['truename'] );
        $user['short_name']    = $shortName;
        $avatarUrl             = ImgUpload::getOneValueById( $user['avatar'], 'img_url' );
        if( $avatarUrl ){
            $avatarHttp        = Func::getImgUrlHttp( $avatarUrl );
        } else {
            $avatarHttp        = asset('upload/appicon/logo.png');
        }
        $user['avatar_http']  = $avatarHttp;

        $companyList           = DepartmentUser::getCompanyListByUserId( $userId );
        foreach( $companyList as $key=>$val ){
            $isDefault         = 0;
            if( $val['id'] == $user['company_id'] ){
                $isDefault     = 1;
            }
            $companyList[$key]['is_default']   = $isDefault;
        }

        $result         = [
            'user'=>$user, 'company_list'=>$companyList
        ];
        return $result;
    }
    public function setting()
    {
        $userId            = Func::getHeaderValueByName( 'userid' );
        if( !$userId ){
            xThrow( ERR_PARAMETER );
        }
        $fieldsArr         = [
            ['name'=>'truename', 'value'=>''],['name'=>'truename_hide', 'value'=>0],
            ['name'=>'avatar', 'value'=>0],['name'=>'sex', 'value'=>0],
            ['name'=>'mobile_hide', 'value'=>0],
            ['name'=>'birthday', 'value'=>''],['name'=>'address', 'value'=>''],
            ['name'=>'province_id', 'value'=>0],['name'=>'city_id', 'value'=>0],
            ['name'=>'area_id', 'value'=>0]
        ];
        $data               = [];
        foreach( $fieldsArr as $key=>$val ){
            $fieldsName    = $val['name'];
            $fieldsValue   = $val['name'];
            $$fieldsName = request( $fieldsName, $fieldsValue );
            if( $$fieldsName != $fieldsValue ){
                switch ($fieldsName){
                    case 'birthday':
                        $birthTime         = strtotime( $birthday );
                        if( $birthTime ){
                            $data['birth_time'] = $birthTime;
                        }
                        break;
                    default:
                        $data[$fieldsName]       = $$fieldsName;
                }
            }
        }
        if( empty($data) ){
            xThrow( ERR_PARAMETER );
        }
        $where              = ['id'=>$userId];

        if(isset($data['truename'])){
            //判断用户名是否已经被占用
            $temp = User::where(['truename'=>$data['truename']])->first();
            if($temp){
                $temp = $temp->toArray();
                if($temp['id'] != $userId){
                    xThrow(ERR_USERNAME_EXIST);
                }
            }
        }

        $updateResult       = User::updateOneData( $where, $data );
        if( $updateResult === false ){
            xThrow( ERR_UNKNOWN );
        }
        $user               = User::getInfo($where);
        if(isset($data['truename']) && $data['truename']!='' && $user->company_id!=0)
        {
            DepartmentUser::where('user_id',$userId)->update(['truename'=>$truename]);
        }
        $result             = [];
        return $result;
    }
    public function checkPassword()
    {
        $password           = request( 'password' );
        $userId            = Func::getHeaderValueByName( 'userid' );
        if( !$userId || !$password ){
            xThrow( ERR_PARAMETER );
        }
        $where              = ['id'=>$userId];
        $info               = User::getLoginInfo( $where, $password );
        if( $info['status'] == false ){
            xThrow( LOGIN_PASSWORE_ERROE );
        }
        $result             = ['message'=>'密码验证成功'];
        return $result;
    }
    public function setMobile()
    {
        $userId            = Func::getHeaderValueByName( 'userid' );
        $mobile             = request( 'mobile' );
        $code               = request('code');
        if( !$userId || !$mobile || !$code ){
            xThrow( ERR_PARAMETER );
        }
        $codeResult            = Sms::checkCode( $mobile, $code, 4 );
        if( !$codeResult ){
            xThrow( ERR_CLIENT_CAPTCHA );
        }
        $where              = ['mobile'=>$mobile];
        $info               = User::getInfo( $where );
        if( $info ){
            xThrow( ERR_CLIENT_USER_ALREADY_EXISTS );
        }
        $where              = ['id'=>$userId];
        $data               = ['mobile'=>$mobile];
        $result             = User::updateOneData( $where, $data );
        if( $result === false ){
            xThrow( ERR_UNKNOWN );
        }
        $where              = ['user_id'=>$userId];
        $data               = ['mobile'=>$mobile];
        DepartmentUser::updateOneData( $where, $data );

        $result             = ['message'=>'修改成功'];
        return $result;
    }

}